#include "buffer.h"

namespace TinyRPC{

// 将所有的
std::string Buffer::read(){
    int old_readIndex = m_readIndex;
    
    std::string str =  std::string(&m_buf[m_readIndex],m_writeIndex - m_readIndex);
    //m_buf.erase(m_buf.begin(), m_buf.begin()+m_readIndex);
    m_readIndex = m_writeIndex = 0;
    return str;
}

std::string Buffer::read(int byteLen){
    int old_readIndex = m_readIndex;
    m_readIndex += byteLen;
    std::string str =  std::string(&m_buf[old_readIndex],byteLen);

    //m_buf.erase(m_buf.begin(), m_buf.begin()+m_readIndex);
    if(m_readIndex == m_writeIndex){
        m_readIndex = m_writeIndex = 0;
    }
    
    return str;
}

// 只是查看, 并没有真正的取走
std::string Buffer::retrieve(int byteLen){
    std::string str =  std::string(&m_buf[m_readIndex],byteLen);
    return str;
}

void Buffer::append(char* str, int strlen){
    int old_writeIndex = m_writeIndex;
    m_writeIndex += strlen;
    m_buf.reserve(m_writeIndex);
    for(int i=0;i<strlen;i++){
        m_buf[i+old_writeIndex] = str[i];
    }
}

void Buffer::append(const std::string& str){
    int old_writeIndex = m_writeIndex;
    m_writeIndex += str.size();
    m_buf.reserve(m_writeIndex);
    for(int i=0;i<str.size();i++){
        m_buf[i+old_writeIndex] = str[i];
    }
}

char* Buffer::charAt(int idx){
    return &m_buf[idx];
}

int Buffer::size(){
    return m_buf.size();
}

Buffer::Buffer()
: m_writeIndex(0)
, m_readIndex(0){

}

int Buffer::getReadableLen(){
    return m_writeIndex - m_readIndex;
}

// 修改读指针
void Buffer::addReadIndex(int val){
    m_readIndex += val;
    if(m_readIndex == m_writeIndex){
        m_readIndex = m_writeIndex = 0;
    }
}

char* Buffer::charAtReadBegin(){
    return charAt(m_readIndex);
}
}